/*
 * CmdCommand.cpp
 *
 *  Created on: Sep 11, 2011
 *      Author: Gherman Alin
 */

#include "CmdCommand.h"
#include <boost/algorithm/string.hpp>
#include <list>

namespace CommandLine {

const std::map<std::string, ParamKey> createStrToKeyMap() {
	std::map<std::string, ParamKey> m;
	m["-o"] = PARAM_OLD_PASS;
	m["-p"] = PARAM_PASS;
	m["-k"] = PARAM_KEY;
	m["-s"] = PARAM_STR_VALUE;
	m["-d"] = PARAM_DATA_VALUE;
	m["-c"] = PARAM_CONTAINER;
	m["-f"] = PARAM_PATH;
	return m;
}

const std::map<std::string, CmdType> createStrToCmdMap() {
	std::map<std::string, CmdType> m;
	m["update"] = CMD_SET_CONTAINER;
	m["delete"] = CMD_REMOVE_CONTAINER;
	m["listc"] = CMD_LIST_CONTAINERS;

	m["list"] = CMD_LIST;
	m["get"] = CMD_GET;
	m["set"] = CMD_SET;
	m["rem"] = CMD_REMOVE;

	m["load"] = CMD_LOAD_FILE;
	m["save"] = CMD_SAVE_FILE;
	m["quit"] = CMD_QUIT;

	return m;
}

const std::map<std::string, ParamKey> CmdCommand::strToKeyMap = createStrToKeyMap();
const std::map<std::string, CmdType> CmdCommand::strToCmdMap = createStrToCmdMap();

CmdCommand::CmdCommand(const std::string& cmdLine) :
		Worker::Command("Text Command Line") {
	std::list<std::string> strs;
	boost::split(strs, cmdLine, boost::is_any_of("\t "));

	std::map<std::string, CmdType>::const_iterator cmdIt = strToCmdMap.find(strs.front());
	cmd = INVALID_CMD;
	if (cmdIt != strToCmdMap.end()) {
		cmd = cmdIt->second;
	}

	strs.pop_front();

	std::list<std::string>::iterator it;
	std::map<std::string, ParamKey>::const_iterator keyIt;
	for (it = strs.begin(); it != strs.end(); it++) {
		if ((*it).length() > 2) {
			std::string k = (*it).substr(0, 2);
			std::string val = (*it).substr(2);
			keyIt = strToKeyMap.find(k);
			ParamKey key = INVALID_PARAM;
			if (keyIt != strToKeyMap.end()) {
				key = keyIt->second;
			}
			params[key].push_back(val);
		}
		else {
			params[INVALID_PARAM].push_back(*it);
		}
	}
}

CmdCommand::~CmdCommand() {
}

void CmdCommand::onSuccess(const std::string& msg) {
}

void CmdCommand::onFailure(const std::string& msg) {
}

CmdType CmdCommand::getCmd() {
	return cmd;
}

std::string* CmdCommand::getParam(ParamKey key) {
	if (params.find(key) == params.end()) {
		return NULL;
	}
	if (params[key].size() == 0) {
		return NULL;
	}
	std::list<std::string>& l = params[key];
	return &(l.front());
}

std::list<std::string> CmdCommand::getParams(ParamKey key) {
	if (params.find(key) == params.end()) {
		return std::list<std::string>();
	}
	if (params[key].size() == 0) {
		return std::list<std::string>();
	}
	return params[key];
}

std::string CmdCommand::helpMsg() {
	return std::string("help not implemented yet");
}

}
